package com.itboye.sunsun.choosecity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.map.RegionActivity;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.choosecity.MyLetterListView.OnTouchingLetterChangedListener;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.custome.FlowLayout;
import com.itboye.sunsun.custome.MyListView;
import com.itboye.sunsun.db.CityNoDBManager;
import com.itboye.sunsun.db.DBManager;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsunhome.R;
import com.itboye.sunsunhome.util.Byalert;
import com.umeng.socialize.utils.Log;

/**
 * 城市列表
 * 
 * @author sy
 * 
 */
public class CityListActivity extends BaseActivity implements OnClickListener {
	private BaseAdapter adapter;
	private ListView city_list;
	private TextView overlay;
	private MyLetterListView cityLetterListView;
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private Handler handler;
	private OverlayThread overlayThread;
	private SQLiteDatabase database;
	private ArrayList<CityModel> mCityNames;
	private ImageView close_icon;
	private TextView gpsTv;
	EditText edit_inputcity;
	ImageView tvMapCity;
	private FlowLayout area_container;
	boolean isArea = true;
	private ArrayList<CityModel> arrayLitArea;// 区域列表
	private DBManager dbManager;
	public String city, resultDatas;
	int type = 1;// 1、直辖市 2、城市
	boolean searchType = true;// true、根据 城市搜索店铺 false、根据地区搜索店铺
	private LocationManager locationManager = null;
	private static final int EXPIRE_TIME = 1000 * 60 * 1;// 这个可是根据软件的需要调整
	private Location curLocation = null;
	private Geocoder geocoder = null;
	private String curAddr = "";
	String latLongString;
	Double a, b;
	private TextView tvLoaction;
	// private TextView showJW = null;

	private double latitude = 0;

	private double longitude = 0;
	boolean isGPS = true;

	private Handler handlers = new Handler() {
		public void handleMessage(android.os.Message msg) {
			double[] data = (double[]) msg.obj;
			// LocTxtView.setText("经度：" + data[0] + "\t纬度:" + data[1]);

			List<Address> addList = null;
			Geocoder ge = new Geocoder(getApplicationContext());
			try {
				addList = ge.getFromLocation(data[0], data[1], 1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (addList != null && addList.size() > 0) {
				for (int i = 0; i < addList.size(); i++) {
					Address ad = addList.get(i);
					latLongString = ad.getLocality();
				}
			}
			gpsTv.setText("" + latLongString);
		}

	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_list);
		setStatusBarColor(R.color.home_blue);
		close_icon.setOnClickListener(this);
		gpsTv = (TextView) findViewById(R.id.gpsTv);
		// gpsRemind= (TextView) findViewById(R.id.gpsTv);
		gpsTv.setText(SPUtils.get(this, null, SPContants.SELECT_CITY, "") + "");
		tvLoaction = (TextView) findViewById(R.id.tvLoaction);
		// gpscity.setText(SPUtils.get(this, null, SPContants.SELECT_CITY, "") +
		// "");

		gpsTv.setOnClickListener(this);
		area_container = (FlowLayout) findViewById(R.id.area_container);
		tvMapCity = (ImageView) findViewById(R.id.tvMapCity);
		// cityNoDBManager = new CityNoDBManager(this);
		dbManager = new DBManager(this);
		dbManager.openDateBase();
		// cityNoDBManager.openDateBase();
		database = SQLiteDatabase.openOrCreateDatabase(DBManager.DB_PATH + "/"
				+ DBManager.DB_NAME, null);
		city = getIntent().getStringExtra("resultDatas");
		String resultData = (String) SPUtils.get(App.ctx, null,
				SPContants.isqu, "");

		if (city != null) {
			afterCitySelected(city);
		} else {

		}
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		System.out.println("rssuwerwle" + resultData);
		System.out.println("resultDatas" + resultDatas);
		edit_inputcity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(CityListActivity.this,
						RegionActivity.class);
				finish();
				startActivityForResult(intent, 101);
			}
		});
		// dbManager.closeDatabase();

		mCityNames = getCityNames();
		// database.close();
		cityLetterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
		alphaIndexer = new HashMap<String, Integer>();
		handler = new Handler();
		overlayThread = new OverlayThread();

		initOverlay();
		setAdapter(mCityNames);
		city_list.setOnItemClickListener(new CityListOnItemClick());
		new Thread() {
			@Override
			public void run() {
				Location location = locationManager
						.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
				if (location != null) {
					latitude = location.getLatitude(); // 经度
					longitude = location.getLongitude(); // 纬度
					double[] data = { latitude, longitude };
					Message msg = handlers.obtainMessage();
					msg.obj = data;
					handlers.sendMessage(msg);
				}
			}
		}.start();

	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 101 && arg1 == 102) {
			afterCitySelected(arg2.getStringExtra("city"));
			System.out.println("cityytyttt" + arg2.getStringExtra("city"));
		}
	}

	public static void goToCityListActivity(Context context) {
		Intent intent = new Intent(context, CityListActivity.class);
		context.startActivity(intent);
	}

	/**
	 * 从数据库获取城市数据
	 * 
	 * @return
	 */
	private ArrayList<CityModel> getCityNames() {
		ArrayList<CityModel> names = new ArrayList<CityModel>();
		Cursor cursor = database.rawQuery(
				"SELECT * FROM T_City ORDER BY NameSort", null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			CityModel cityModel = new CityModel();
			cityModel.setCityName(cursor.getString(cursor
					.getColumnIndex("CityName")));
			cityModel.setNameSort(cursor.getString(cursor
					.getColumnIndex("NameSort")));
			names.add(cityModel);
		}
		return names;
	}

	/**
	 * 城市列表点击事件
	 * 
	 * @author sy
	 * 
	 */
	class CityListOnItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3) {

			searchType = true;
			CityModel cityModel = (CityModel) city_list.getAdapter().getItem(
					pos);
			city = cityModel.getCityName();
			String cityCode = cityModel.getCityCode();
			SPUtils.put(CityListActivity.this, null, SPContants.SELECT_CITY,
					cityModel.getCityName());

			// city_list.smoothScrollToPosition(0);
			// city_list.setSelection(0);// 设置选择项为第一项
			finish();

			Intent intent = new Intent();
			intent.putExtra("number", cityModel.getNameSort());
			intent.putExtra("province", cityModel.getCityName());
			setResult(104, intent);
			SPUtils.put(App.ctx, null, SPContants.PROVINCE,
					cityModel.getCityName());
			SPUtils.put(App.ctx, null, SPContants.chengshi, "chengshi");
			System.out.println("citycitycity" + cityModel.getNameSort());

			Intent intent2 = new Intent("resultData");
			sendBroadcast(intent2);
		}

	}

	private void afterCitySelected(String city) {

		String cityCode = "";
		SPUtils.put(this, null, SPContants.SELECT_CITY, city);
		gpsTv.setText("重新定位");
		// Intent intent = new Intent();
		// intent.putExtra("choose", city);
		// setResult(102,intent);
		if (city.equals("重庆市") || city.equals("北京市") || city.equals("天津市")// 特殊直辖市
				|| city.equals("上海市")) {
			type = 1;
			// cityCode = dbManager.queryPriovinceNo(city);
			Cursor cursor = database.rawQuery(
					"SELECT provinceID from hat_province where province = ?",
					new String[] { city });
			if (cursor != null) {
				while (cursor.moveToNext()) {
					cityCode = cursor.getString(cursor
							.getColumnIndexOrThrow("provinceID"));
				}
			}
			cityCode = cityCode.substring(0, cityCode.length() - 4);
			// Cursor
			// cursor2=database.rawQuery("SELECT provinceID from hat_province where province = ?",new
			// String[]{});

		} else {
			type = 2;
			Cursor cursor = database.rawQuery(
					"SELECT cityID from hat_city where city = ?",
					new String[] { city });
			if (cursor != null) {
				while (cursor.moveToNext()) {
					cityCode = cursor.getString(cursor
							.getColumnIndexOrThrow("cityID"));
				}
			}
			cursor.close();
			// cityCode = dbManager.queryCityNo(city);
		}
		arrayLitArea = new ArrayList<>();
		arrayLitArea = queryArea(cityCode);
		System.out.println("arrayLitArea" + arrayLitArea);
		addArea(arrayLitArea);

		// if (arrayLitArea == null) {
		// area_container.setVisibility(View.GONE);
		// } else {
		//
		// }
	}

	/***
	 * 查询区域列表
	 * 
	 * @param cityName
	 * @return
	 */
	public ArrayList<CityModel> queryArea(String cityNo) {
		Cursor cursor = null;
		ArrayList<CityModel> arrayArea = new ArrayList<>();
		if (database != null)
			cursor = database.query("hat_area", null, "father like ?",
					new String[] { cityNo + "%" }, null, null, null);
		if (cursor != null)
			while (cursor.moveToNext()) {
				CityModel cityModel = new CityModel();
				cityModel.setAreaCode(cursor.getString(cursor
						.getColumnIndexOrThrow("areaID")));
				cityModel.setCityCode(cursor.getString(cursor
						.getColumnIndexOrThrow("father")));
				cityModel.setAreaName(cursor.getString(cursor
						.getColumnIndexOrThrow("area")));
				arrayArea.add(cityModel);
			}
		cursor.close();
		// database.close();
		return arrayArea;
	}

	private void addArea(ArrayList<CityModel> array) {
		System.out.println(">>>>>>>>>>>>>>>>" + array);
		area_container.removeAllViews();
		for (int i = 0; i < array.size(); i++) {
			CityModel array_element = array.get(i);
			final TextView textView = new TextView(this);

			textView.setText(array_element.getAreaName());
			textView.setTag(array_element.getAreaCode());
			textView.setTextSize(15);
			textView.setPadding(10, 10, 10, 10);
			textView.setBackground(getResources().getDrawable(
					R.drawable.btn_choose_city));
			android.widget.LinearLayout.LayoutParams layoutParams = new android.widget.LinearLayout.LayoutParams(
					android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
					android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
			layoutParams.setMargins(5, 5, 5, 5);

			area_container.addView(textView,
					area_container.getChildCount() - 1, layoutParams);
			textView.setTag(R.id.tag_first, array_element.getAreaName());
			textView.setTag(R.id.tag_second, array_element.getAreaCode());

			textView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					searchType = false;
					SPUtils.put(CityListActivity.this, null,
							SPContants.SELECT_AREA,
							textView.getTag(R.id.tag_first) + "");
					Log.v("cityId", textView.getTag(R.id.tag_second) + "");
					SPUtils.put(CityListActivity.this, null,
							SPContants.SELECT_AREA_CODE,
							textView.getTag(R.id.tag_second) + "");

					SPUtils.put(CityListActivity.this, null, SPContants.isqu,
							"quxian");
					Intent intent = new Intent();
					intent.putExtra("provinces",
							"" + textView.getTag(R.id.tag_first));
					intent.putExtra("numbers", textView.getTag(R.id.tag_second)
							+ "");
					intent.putExtra("type", type);
					intent.putExtra("searchType", searchType);
					setResult(106, intent);
					finish();
				}
			});
		}
	}

	/**
	 * 为ListView设置适配器
	 * 
	 * @param list
	 */
	private void setAdapter(List<CityModel> list) {

		// LayoutInflater layoutInflater = (LayoutInflater)
		// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		// View headview = layoutInflater.inflate(R.layout.inculd_city_headview,
		// null);
		// area_container = (FlowLayout) headview
		// .findViewById(R.id.area_container);
		// TextView tvMapCity = (TextView)
		// headview.findViewById(R.id.tvMapCity);
		tvMapCity.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String resultData = (String) SPUtils.get(App.ctx, null,
						SPContants.isqu, "");
				String chengshi = (String) SPUtils.get(App.ctx, null,
						SPContants.chengshi, "");

					if (isArea) {
						isArea = false;
						area_container.setVisibility(View.GONE);
					} else {
						isArea = true;
						area_container.setVisibility(View.VISIBLE);
				}
			}
		});

		String gpsCity = SPUtils.get(this, null, SPContants.SELECT_CITY, "")
				+ "";
		if (gpsCity.equals("")) {
			// gpsTv.setText("杭州");
			tvLoaction.setText("还未选取城市");
		} else {
			tvLoaction.setText(gpsCity);
			
		}

		// city_list.addHeaderView(headview);
		if (list != null) {
			adapter = new ListAdapter(this, list);
			city_list.setAdapter(adapter);
		}

	}

	private void setClickLis(TextView tv, final String name) {
		tv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				afterCitySelected(name);
			}
		});
	}

	/**
	 * ListViewAdapter
	 * 
	 * @author sy
	 * 
	 */
	private class ListAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<CityModel> list;

		public ListAdapter(Context context, List<CityModel> list) {

			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++) {
				// 当前汉语拼音首字母
				// getAlpha(list.get(i));
				String currentStr = list.get(i).getNameSort();
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? list.get(i - 1)
						.getNameSort() : " ";
				if (!previewStr.equals(currentStr)) {
					String name = list.get(i).getNameSort();
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.name.setText(list.get(position).getCityName());
			String currentStr = list.get(position).getNameSort();
			String previewStr = (position - 1) >= 0 ? list.get(position - 1)
					.getNameSort() : " ";
			if (!previewStr.equals(currentStr)) {
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			} else {
				holder.alpha.setVisibility(View.GONE);
			}
			return convertView;
		}

		private class ViewHolder {
			TextView alpha;
			TextView name;
		}

	}

	// 初始化汉语拼音首字母弹出提示框
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		WindowManager windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s) + 1;
				city_list.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.GONE);
				handler.removeCallbacks(overlayThread);
				// 延迟一秒后执行，让overlay为不可见
				handler.postDelayed(overlayThread, 1500);
			}
		}

	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.close_icon:
			finish();
			break;
		case R.id.gpsTv:
			// LocManager.getInstance().startLocOnce(this);
			break;
		default:
			break;
		}
	}

}